package com.zhuiyun.project.security.commonhandler;

import com.zhuiyun.project.api.sysuser.entiy.SysUser;
import com.zhuiyun.project.api.sysuser.mapper.SysUserMapper;
import com.zhuiyun.project.api.sysuser.service.SysUserService;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.common.response.ResponseUtil;
import com.zhuiyun.project.security.jwt.JWTConfig;
import com.zhuiyun.project.security.jwt.JWTUtils;
import com.zhuiyun.project.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * @ClassName AuthenticationSuccessHandler
 * @Description 后台登录成功的操作
 * @Author zcy
 * @Date 2023/3/27 11:20
 **/
@Component
public class SysUserLoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    SysUserService sysUserService;
   @Autowired
   SysUserMapper sysUserMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
               SysUser user = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
               user.setLastLoginTime(new Date());
               user.setUpdateTime(new Date());
               // 获取登录ip
               user.setLastLoginIp(request.getLocalAddr());
               sysUserService.updateUserByLogin(user);
               String token = JWTUtils.createAccessToken(user);
               // 设置token过期时间
               RedisUtil.set(token, user, JWTConfig.expiration);
               token = JWTConfig.tokenPrefix + token;
               HashMap<String, Object> hashMap = new HashMap<>();
               hashMap.put("avatarUrl", user.getAvatarId());
               hashMap.put("token", token);
               hashMap.put("userId", user.getId());
               hashMap.put("loginName", user.getLoginName());
               // 将token 放入redis中
               ResponseUtil.responseJson(response, CommonResult.ok(hashMap));
    }
}
